import Axios from 'axios'
import {ElMessage} from 'element-plus'
const config = {
    baseURL: import.meta.env.NODE_ENV === "production" ? "http://101.133.234.110:11202/" : "cimapi",
    timeout:50000
}

const request = Axios.create(config)

// 请求拦截
let token
request.interceptors.request.use((config)=>{
    token = localStorage.getItem("token")
    if(token){
        config.header["Authorization"] = token
    }
    config.headers["Content-Encoding"] = "gzip"
    return config
})


// 响应拦截
request.interceptors.response.use((res)=>{
    return res.result || res.data || res
},(err)=>{
    messageError(err)
})

//响应错误提示
function messageError(error){
    console.error(error)
    if(error.response){
        ElMessage.error("message",error.response.status + ":" + error.response.data)
    }
}

// 合并多个请求
export function mergeRequest(requests,responses=[]){
    let args = []
    args = requests.map((arg)=>(
        async function(){
            let query = ""
            if(arg.query){
                query = "?" + queryJson(arg.query)
            }
            return await request({
                method:arg.method || "get",
                header:arg.header || {},
                data:arg.data,
                url:(arg.url || arg.path || arg.src) + query
            })
        }
        
    ))
    return Promise.all(args,responses)
}
export function queryJson(query){
    let k,str =""
    for(k in query){
        str+=`${k}=${query[k]}&`
    }
    return str.substring(0,str.length - 1)
}
export default request